package net.documentshare.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.documentshare.i.IItSiteApplicationModule;
import net.documentshare.i.ISendMail;
import net.simpleframework.ado.DataObjectManagerUtils;
import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.SQLValue;
import net.simpleframework.ado.db.event.ITableEntityListener;
import net.simpleframework.ado.lucene.AbstractLuceneManager;
import net.simpleframework.applets.notification.MailMessageNotification;
import net.simpleframework.applets.notification.NotificationUtils;
import net.simpleframework.content.AbstractContentApplicationModule;
import net.simpleframework.core.ExecutorRunnable;
import net.simpleframework.core.IInitializer;
import net.simpleframework.core.ITaskExecutorAware;
import net.simpleframework.core.bean.AbstractIdDataObjectBean;
import net.simpleframework.core.id.ID;
import net.simpleframework.organization.IUser;
import net.simpleframework.util.ConvertUtils;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.WebUtils;
import net.simpleframework.web.page.PageRequestResponse;
import net.simpleframework.web.page.component.AbstractComponentBean;
import net.simpleframework.web.page.component.ComponentParameter;

/**
 * 
 * @Description：
 * @author: 李岩飞
 * @Time: 2011-7-28 下午1:42:05 
 */
public abstract class AItSiteAppclicationModule extends AbstractContentApplicationModule implements IItSiteApplicationModule {

	@Override
	public void doUpdate(Object[] columns, Object bean) {
		final ITableEntityManager tMgr = getDataObjectManager(bean.getClass());
		if (tMgr != null) {
			tMgr.update(columns, bean);
		}
	}

	@Override
	public void doUpdate(Object[] columns, Object bean, ITableEntityListener tel) {
		final ITableEntityManager tMgr = getDataObjectManager(bean.getClass());
		if (tMgr != null) {
			tMgr.updateTransaction(columns, bean, tel);
		}
	}

	@Override
	public ITableEntityManager getDataObjectManager() {
		return DataObjectManagerUtils.getTableEntityManager(this);
	}

	@Override
	public ITableEntityManager getDataObjectManager(Class<?> t) {
		return DataObjectManagerUtils.getTableEntityManager(this, t);
	}

	@Override
	public void doUpdate(String sql) {
		final ITableEntityManager entityManager = getDataObjectManager();
		entityManager.execute(new SQLValue(sql));
	}

	@Override
	public void doUpdate(List<? extends AbstractIdDataObjectBean> beanList) {
		for (AbstractIdDataObjectBean bean : beanList) {
			doUpdate(bean);
		}
	}

	@Override
	public String getViewUrl(Object id) {
		return null;
	}

	@Override
	public void doUpdate(AbstractIdDataObjectBean bean, ITableEntityListener tel) {
		final ITableEntityManager entityManager = getDataObjectManager(bean.getClass());
		if (bean.getId() == null) {
			bean.setId(ID.Utils.newID(entityManager.nextIncValue("id")));
			entityManager.insertTransaction(bean, tel);
		} else {
			entityManager.updateTransaction(bean, tel);
		}
	}

	@Override
	public void doDelete(AbstractIdDataObjectBean bean, ITableEntityListener tel) {
		final ITableEntityManager entityManager = getDataObjectManager(bean.getClass());
		if (entityManager != null)
			entityManager.deleteTransaction(new ExpressionValue("id=?", new Object[] { bean.getId() }), tel);
	}

	@Override
	public void init(IInitializer initializer) {
		super.init(initializer);
	}

	@Override
	public void doUpdate(AbstractIdDataObjectBean bean) {
		final ITableEntityManager entityManager = getDataObjectManager(bean.getClass());
		if (bean.getId() == null) {
			bean.setId(ID.Utils.newID(entityManager.nextIncValue("id")));
			entityManager.insert(bean);
		} else {
			entityManager.update(bean);
		}
	}

	@Override
	public void doDelete(final AbstractIdDataObjectBean bean) {
		final ITableEntityManager entityManager = getDataObjectManager(bean.getClass());
		if (entityManager != null)
			entityManager.delete(new ExpressionValue("id=?", new Object[] { bean.getId() }));
	}

	@Override
	public void doDelete(Class<?> bean, Object id) {
		final ITableEntityManager entityManager = getDataObjectManager(bean);
		if (entityManager != null)
			entityManager.delete(new ExpressionValue("id=?", new Object[] { id }));
	}

	@Override
	public void doDelete(List<? extends AbstractIdDataObjectBean> beanList) {
		for (final AbstractIdDataObjectBean bean : beanList) {
			doDelete(bean);
		}
	}

	@Override
	public void doDelete(List<? extends Object> idList, Class<? extends Object> beanClass) {
		for (final Object id : idList) {
			doDelete(beanClass, id);
		}
	}

	@Override
	public void doDelete(Class<?> bean, Object id, ITableEntityListener tel) {
		final ITableEntityManager entityManager = getDataObjectManager(bean);
		if (entityManager != null)
			entityManager.deleteTransaction(new ExpressionValue("id=?", new Object[] { id }), tel);
	}

	@Override
	public void doDelete(final PageRequestResponse requestResponse) {
	}

	@Override
	public IQueryEntitySet<Map<String, Object>> queryBean(String sql, final Object[] values) {
		final ITableEntityManager tMgr = getDataObjectManager();
		return tMgr.query(new SQLValue(sql, values));
	}

	@Override
	public <T> IQueryEntitySet<T> queryBean(String exp, Class<T> t) {
		final ITableEntityManager tMgr = getDataObjectManager(t);
		return tMgr.query(new ExpressionValue(exp == null ? "1=1" : exp), t);
	}

	@Override
	public <T> IQueryEntitySet<T> queryBean(String exp, Object[] values, Class<T> t) {
		final ITableEntityManager tMgr = getDataObjectManager(t);
		return tMgr.query(new ExpressionValue(exp == null ? "1=1" : exp, values), t);
	}

	@Override
	public <T> List<T> doQuery(String sql, String col, Class<T> t) {
		final List<T> list = new ArrayList<T>();
		final ITableEntityManager tMgr = getDataObjectManager(t);
		final IQueryEntitySet<Map<String, Object>> qs = tMgr.query(new SQLValue(sql));
		if (qs != null) {
			Map<String, Object> data;
			while ((data = qs.next()) != null) {
				try {
					list.add(t.cast(data.get(col)));
				} catch (Exception e) {
				}
			}
		}
		return list;
	}

	@Override
	public void doDelete(final String where, Class<?> bean) {
		final ITableEntityManager entityManager = getDataObjectManager(bean);
		if (entityManager != null)
			entityManager.deleteTransaction(new SQLValue("delete from " + entityManager.getTablename() + " where " + where));
	}

	@Override
	public <T> T getBean(Class<T> t, Object id) {
		final ITableEntityManager tMgr = getDataObjectManager(t);
		return tMgr.queryForObjectById(id, t);
	}

	@Override
	public <T> T getBeanByExp(Class<T> t, String exp, final Object[] params) {
		final ITableEntityManager tMgr = getDataObjectManager(t);
		return tMgr.queryForObject(new ExpressionValue(exp, params), t);
	}

	@Override
	public AbstractComponentBean getComponentBean(PageRequestResponse requestResponse) {
		return null;
	}

	@Override
	public String tabs(PageRequestResponse requestResponse) {
		return null;
	}

	public AbstractLuceneManager createLuceneManager(final ComponentParameter compParameter) {
		return null;
	}

	final static Map<String, String> orderData = new LinkedHashMap<String, String>();
	static {
		orderData.put("new", "最新");
		orderData.put("popular", "最多阅读");
		orderData.put("grade", "最高评价");
		orderData.put("remark", "最新评论");
	}

	/**
	 * 获得参数
	 * @param requestResponse
	 * @return
	 */
	protected String getParameters(PageRequestResponse requestResponse) {
		return null;
	}

	protected Map<String, String> getOrderData() {
		return new LinkedHashMap<String, String>(orderData);
	}

	public String tabs13(PageRequestResponse requestResponse) {
		final StringBuffer buf = new StringBuffer();
		final String applicationUrl = getApplicationUrl(requestResponse);
		final String param = getParameters(requestResponse);
		final String temp = StringUtils.text(requestResponse.getRequestParameter("od"), "new");
		int i = 0;
		Map<String, String> orderData = getOrderData();
		for (final String od : orderData.keySet()) {
			buf.append("<a hidefocus=\"hidefocus\"");
			String p = "od=" + od;
			if (StringUtils.hasText(param)) {
				p = param + "&" + p;
			}
			buf.append(" href=\"" + WebUtils.addParameters(applicationUrl, p) + "\"");
			if (od.equals(temp)) {
				buf.append(" class=\"a2 nav_arrow\"");
			}
			buf.append(">").append(orderData.get(od)).append("</a>");
			if (i++ != orderData.size() - 1) {
				buf.append("<span style=\"margin: 0px 4px;\">|</span>");
			}
		}
		return buf.toString();
	}

	@Override
	public void deleteAttentions(Object documentId) {
	}

	@Override
	public long getValue(String sql, Object[] values) {
		final ITableEntityManager tMgr = getDataObjectManager();
		final IQueryEntitySet<Map<String, Object>> qs = tMgr.query(new SQLValue(sql, values));
		if (qs == null)
			return 0;
		Map<String, Object> data;
		while ((data = qs.next()) != null) {
			return ConvertUtils.toLong(data.get(data.keySet().iterator().next()), 0);
		}
		return 0;
	}

	@Override
	public AbstractAttention getAttention(Object userId, Object id) {
		return null;
	}

	protected void doAttentionMail(final ComponentParameter compParameter, final ISendMail sendMail) {
		((ITaskExecutorAware) getApplication()).getTaskExecutor().execute(new ExecutorRunnable() {
			@Override
			public void task() {
				final MailMessageNotification mailMessage = new MailMessageNotification();
				mailMessage.setHtmlContent(true);
				final IUser user = sendMail.getUser();
				if (sendMail.isSent(user)) {
					mailMessage.getTo().add(user);
					mailMessage.setSubject(sendMail.getSubject(user));
					mailMessage.setTextBody(sendMail.getBody(user));
					NotificationUtils.sendMessage(mailMessage);
				}
			}
		});
	}
}
